import { BadRequestException, HttpCode, Injectable } from '@nestjs/common';
import { CreateDictItemDto } from './dto/create-dict-item.dto';
import { UpdateDictItemDto } from './dto/update-dict-item.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { DictItem } from './entities/dict-item.entity';
import { Like, Repository } from 'typeorm';
import { DictTypeService } from '../dict-type/dict-type.service';
import { QueryDictItemDto } from './dto/query-dict-item.dto';

@Injectable()
export class DictItemService {
  constructor(
    @InjectRepository(DictItem)
    private dictItemRepository: Repository<DictItem>,
    private dictTypeService: DictTypeService,
  ) {}
  async create(createDictItemDto: CreateDictItemDto) {
    const { dictId } = createDictItemDto;
    const data = await this.dictTypeService.findOne(dictId);
    if (!data) {
      throw new BadRequestException('字典类型不存在');
    }

    const dictItemData = await this.dictItemRepository.create({
      ...createDictItemDto,
      dictType: data,
    });
    return await this.dictItemRepository.save(dictItemData);
  }

  async findAll(queryDictItemDto: QueryDictItemDto) {
    const { label, value, dictCode } = queryDictItemDto;
    return {
      data: await this.dictItemRepository.find({
        where: {
          dictType: {
            dictCode: dictCode,
          },
          ...(label && { label: Like(`%${label}%`) }),
          ...(value && { value: value }),
        },
      }),
    };
  }

  async findOne(id: number) {
    return await this.dictItemRepository.findOne({ where: { id } });
  }

  async update(id: number, updateDictItemDto: UpdateDictItemDto) {
    const merge = await this.findOne(id);
    this.dictItemRepository.merge(merge, updateDictItemDto);
    return await this.dictItemRepository.save(merge);
  }

  remove(id: number) {
    return this.dictItemRepository.delete(id);
  }
}
